﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Wenyu.Framework.DbModels.Entities;

namespace Wenyu.Framework.WebCore.ToolServices
{
    public class JwtToolService
    {
        private readonly JwtTokenOption _jwtOption;

        public JwtToolService(IOptionsMonitor<JwtTokenOption> optionsMonitor)
        {

            _jwtOption = optionsMonitor.CurrentValue;
        }

        public string GetToken(UserEntity user)
        {
            //有效载荷
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,user.Name),
                new Claim(ClaimTypes.Role,"admin"),
                new Claim(ClaimTypes.Role,"teacher"),

                new Claim("UserId",user.UserId.ToString()),
                new Claim("UserName",user.UserName),
                //new Claim("Name",user.Name.ToString()),
                new Claim("UserType",user.UserType.ToString()),
            };

            //加密需要加密key
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOption.SecurityKey));

            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: _jwtOption.Issuer,
                audience: _jwtOption.Audiece,
                claims: claims,
                //expires: DateTime.Now.AddMinutes(10),//10分钟过期
                expires: DateTime.Now.AddSeconds(20),//20s过期
                signingCredentials: creds
                );
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }
    }
}
